package com.bupt.liutong.admin.core.filter;

import java.io.IOException;
import java.util.List;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.bupt.liutong.admin.core.dto.Authenticator;
import com.bupt.liutong.util.ListUtils;
import com.bupt.liutong.util.StringUtils;

public class AuthenticateFilter implements Filter {

	public void destroy() {

	}

	@SuppressWarnings("unchecked")
	public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse,
			FilterChain chain) throws IOException, ServletException {
		Authenticator auth = Authenticator.getInstance();
		HttpServletRequest request = (HttpServletRequest) servletRequest;
		HttpServletResponse response = (HttpServletResponse) servletResponse;
		String servletPath = request.getServletPath();
		if (servletPath != null
				&& (servletPath.endsWith(".do") || servletPath.endsWith(".jsp"))
				&& !servletPath.equals("/admin/core/login.do")) {
			String key = servletPath;
			String params = auth.getActionParam(key);
			if (!StringUtils.isEmpty(params)) {
				String[] paramArr = params.split(",");
				key += "?";
				for (int i = 0; i < paramArr.length; i++) {
					if (i > 0)
						key += "&";
					key += paramArr[i] + "=" + request.getParameter(paramArr[i]);
				}
			}

			List<Integer> roleIds = (List<Integer>) request.getSession().getAttribute("roleIds");
			List<Integer> authRoleIds = auth.get(key);
			if (authRoleIds != null && authRoleIds.size() > 0 && !ListUtils.containsOne(authRoleIds, roleIds)) {
				if (key.startsWith("/admin")) {
					response.sendRedirect(request.getContextPath()
							+ "/admin/core/login/not_allowed.jsp");
					return;
				}
				else {
					response.sendRedirect(request.getContextPath()
							+ "/front/sch/user/not_allowed.jsp");
					return;
				}
			}
		}
		chain.doFilter(request, response);
	}

	public void init(FilterConfig filterConfig) throws ServletException {

	}

}
